
INPUT1_NUM_ITEMS_IN_LINE = 10
TITLE_HEADER = "RIC_Name,RT_Number,PE,RDN_EXCHID,RECORDTYPE,RDN_EXCHD2,DSO_ID,VAA_Name,Channel_ID,FIDs"

class RICInfo
	attr :ric, true
	attr :rt_number, true
	attr :pe, true
	attr :rdn_exchid, true
	attr :recordtype, true
	attr :rdn_exchd2, true
	attr :dso_id, true
	attr :vaa, true
	attr :channel, true
	attr :fids, true

	def to_s
		return "=\"#{ric}\", #{rt_number}, #{pe}, #{rdn_exchid}, #{recordtype}, #{rdn_exchd2}, =\"#{dso_id}\", #{vaa}, #{channel}, \"#{fids}\""
	end
end

def update_ric(line, dict)
	items = line.split()
	if items.length == INPUT1_NUM_ITEMS_IN_LINE
		ric = items[0]
		if dict.has_key?(ric)
			ri = dict[ric]
			ri.rt_number = items[1]
			ri.pe = items[2]
			ri.rdn_exchid = items[6]
			ri.recordtype = items[7]
			ri.rdn_exchd2 = items[8]
			ri.dso_id = items[9]
		end
	end
end

def update_dict(filename, dict)
	i = 0
	IO.foreach(filename) do |line|
		line.strip!
		if i > 0 and line.length > 0
			update_ric(line, dict)
		end
		i += 1
		if i % 10000 == 0
			puts "#{filename}: #{i} lines processed."
		end
	end
end

def load_dict(filename, dict)
	i = 0
	channel = -1
	vaa = "(no name)"
	
	IO.foreach(filename) do |line|
		line.strip!
		if line.length > 0
			if line.start_with?("[") and line.end_with?("]")
				items = line.split(/[,|\s]/)
				channel = items[0][1..-1]
				vaa = items[1]
			else
				items = line.split("@")
				ric = items[0].strip
				fids = items[1].strip
				ri = RICInfo.new
				ri.ric = ric
				ri.fids = fids
				ri.vaa = vaa
				ri.channel = channel
				dict[ric] = ri
			end
		end
		i += 1
		if i % 10000 == 0
			puts "#{filename}: #{i} lines processed."
		end
	end
end

def output_dict(dict)
	File.open("output.csv", "w+") do |file|
		dict.each do |key, value|
			file.puts value
		end
	end
end

def split(filename, nlines, prefix, suffix)
	n = 0
	i = 1
	file = nil
	IO.foreach(filename) do |line|
		if n % nlines == 0
			file.close() if not file.nil?
			file = File.new(prefix + i.to_s() + suffix, "w+")
			file.puts(TITLE_HEADER)
			i += 1
		end
		n += 1
		file.puts(line)
	end
	file.close() if not file.nil?
end

def main()
	dict = Hash.new
	puts "Loading input file..."
	load_dict("input2.txt", dict)
	puts "Updating..."
	update_dict("input1.txt", dict)
	puts "Saving result..."
	output_dict(dict)
	puts "Spliting..."
	split("output.csv", 200000, "vapr_", ".csv");
	puts "Finished."
end

main
